package com.zjinyin.forum.controller;

import com.zjinyin.forum.common.AppResult;
import com.zjinyin.forum.common.ResultCode;
import com.zjinyin.forum.exception.ApplicationException;
import com.zjinyin.forum.model.Board;
import com.zjinyin.forum.service.IBoardService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: DELL
 * Date: 2023-08-10
 * Time: 12:01
 */
@Api(tags = "版块接口")
@Slf4j
@RestController
@RequestMapping("/board")
public class BoardController {

    // 从配置文件中读取, 如果没有配置, 默认值为 9
    @Value("${forum.index.board-num : 9}")
    private Integer BOARD_NUM;

    @Resource
    private IBoardService boardService;

    /**
     * 获取导航栏所有版块
     *
     * @return 返回所有的版块对象
     */
    @ApiOperation("获取首页导航栏版块列表")
    @GetMapping("/navigationList")
    public AppResult<List<Board>> navigationList() {
        log.info("配置版块数目 NUM : " + BOARD_NUM);

        List<Board> boards = boardService.selectByNum(BOARD_NUM);

        if (boards == null) {
            boards = new ArrayList<>();
        }

        return AppResult.success(boards);
    }

    /**
     * 获取指定的版块 Id 的信息
     *
     * @param boardId 版块 Id
     * @return 返回指定版块对象
     */
    @ApiOperation("获取指定版块信息")
    @GetMapping("/getBoardInfo")
    public AppResult getBoardInfo(@ApiParam("版块 Id") @RequestParam("boardId") @NonNull Long boardId) {

        // 1. 获取指定 Id 版块
        Board board = boardService.selectById(boardId);

        // 2. 对结果进行校验 - 版块不存在或者已经被删除状态
        if (board == null || board.getDeleteState() == 1) {
            log.warn("boardId : " + board + " " + ResultCode.FAILED_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_NOT_EXISTS));
        }

        return AppResult.success(board);
    }
}
